package infoRetriever;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class TrackListHandler extends DefaultHandler {

	private int noOfTracks;
	private Map<Integer,String> tracks;
	private List<String> orderedTracks;
	
	private String currentTrackName;
	
	private boolean newTrackOpen;
	private boolean releaseOpen;
	private boolean titleOpen;

	
	public TrackListHandler() {
		super();
	}
	
	public int getNoOfTracks() {
		return noOfTracks;
	}

	public List<String> getTracks() {
		return orderedTracks;
	}

	public String toString() {
		String res = "tracks: (" + noOfTracks + ")";
		for(int i = 0; i < noOfTracks; ++i)
			res = res.concat("\n" + (i+1) + ": " + tracks.get(i));
		return res;
	}
	public void startDocument() throws SAXException {
		newTrackOpen = false;
		releaseOpen = false;
		titleOpen = false;
		
		tracks = new HashMap<Integer,String>();
		System.out.println("new");
		orderedTracks = new ArrayList<String>();
	}
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		if(qName.equals("track-list")) {
			if(!releaseOpen)
				noOfTracks = Integer.valueOf(atts.getValue("count")).intValue();
			else
				tracks.put(Integer.valueOf(atts.getValue("offset")), currentTrackName);
		} else if(qName.equals("track")) {
			newTrackOpen = true;
		} else if(qName.equals("release")){
			releaseOpen = true;
		} else if(newTrackOpen && !releaseOpen && qName.equals("title")) {
			titleOpen = true;
		}
	}
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(qName.equals("track")) {
			newTrackOpen = false;
		} else if(qName.equals("release")){
			releaseOpen = false;
		} else if(newTrackOpen && !releaseOpen && qName.equals("title")) {
			titleOpen = false;
		}
	}
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if(titleOpen){
			String help = "";
			for (int i = start; i < start + length; i++) {
			    switch (ch[i]) {
			    case '\\':
			    	help = help.concat("\\\\");
				break;
			    case '"':
			    	help = help.concat("\\\"");
				break;
			    case '\n':
			    	help = help.concat("\\n");
				break;
			    case '\r':
			    	help = help.concat("\\r");
				break;
			    case '\t':
			    	help = help.concat("\\t");
				break;
			    default:
			    	help = help.concat(Character.toString(ch[i]));
				break;
			    }
			}
			currentTrackName = help;
		}
	}
	
	public void endDocument() throws SAXException {
		newTrackOpen = false;
		releaseOpen = false;
		titleOpen = false;
		
		orderedTracks.clear();

		for(int i = 0; i < noOfTracks; ++i)
			orderedTracks.add(tracks.get(i));
		
		tracks.clear();
	}
}
